<?php
namespace App\Logic\Quality;

use App\Logic\Amazon\Api\Orders;
use App\Logic\Amazon\Api\RequiredConfig;
use App\Models\Amazon\AmazonOrder;
use App\Models\Amazon\FbaCustomerReturn;
use App\Models\Basics\AmazonAccount;
use App\Models\Basics\AmazonCountry;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductSku;
use App\Models\Quality\QComplaint;
use App\Models\Quality\QDetail;
use App\Models\Quality\QDict;
use App\Models\Quality\QDictTag;
use Illuminate\Support\Facades\DB;
class Quality
{
    /**
     * 补齐country_id,purchase_date
     * 获取fba退货订单 (更新Amazon订单)
     */
    public static function order(){
        $accounts = AmazonAccount::optionsForApi(['api' => 1]);
        $re = [];
        foreach ($accounts as $account){
            $orderIds = FbaCustomerReturn::query()
                ->whereNull('purchase_date')
                ->where('account_id',$account->id)
                ->take(25)
                ->distinct()
                ->pluck('order_id')
                ->toArray();
            //补齐订单：退货报表里面有但是订单表里面没有，所以需要通过退货报表里order去补齐订单表的order
            $requiredConfig = RequiredConfig::getInit();
            $apiConfig = $requiredConfig->configuration($account->refresh_token,$account->aws_region);
            $flag = Orders::apiGetOrdersViaOrderIDs($apiConfig,$account,$orderIds); //账号下的多订单号
            $re[$account->id] = $flag;

            sleep(2);
            //更新退货报表里的国家和下单时间（退货报表不存在的字段，只能通过orderid到Amazonorder表匹配）
            $orders = AmazonOrder::query()
                ->whereIn('amazon_order_id',$orderIds)
                ->select('amazon_order_id','purchase_date','marketplace_id')
                ->get();
            foreach ($orders as $order){
                $countryId = AmazonCountry::getCountryIdByMarketplaceId($order->marketplace_id);
                FbaCustomerReturn::query()
                    ->whereNull('purchase_date')
                    ->where('account_id',$account->id)
                    ->where('order_id',$order->amazon_order_id)
                    ->update([
                        'purchase_date' => $order->purchase_date,
                        'country_id' => $countryId ?: 0
                    ]);
            }
        }
        var_dump($re);
    }

    /**
     * 统计：客诉
     */
    public static function complaint()
    {
        $date = date('Y-m-01');
        $res = QComplaint::query()->where('status',0)->where('report_date','<',$date)->get();
        $i = 0;
        $num = 100;
        while(true){
            if($res->isEmpty())break;
            $_res = $res->splice($i,$num);
            try{
                DB::beginTransaction();
                foreach($_res as $_re){
                    self::_match($_re->report_date,$_re->country_id,$_re->psku_id,$_re->classify_id,1,$_re->tag);
                    $_re->status = 1; //1:已统计
                    $_re->save();
                }
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }
        }
    }

    /**
     * 统计：FBA客户退货报表
     */
    public static function customerReturn()
    {
        $res = FbaCustomerReturn::query()
            ->select('id','purchase_date','country_id','psku_id','sku','quantity','customer_comments','tag','status')
            ->where('status',0)
            ->get();

        $i = 0;
        $num = 500;
        $exist = [];
        while(true){
            if($res->isEmpty())break;
            $_res = $res->splice($i,$num);
            try{
                DB::beginTransaction();
                foreach($_res as $_re){
                    if(!$_re->customer_comments || !$_re->country_id){
                        $_re->status = 2; //2:无评论
                    }else{
                        if($_re->tag){
                            if(!$_re->psku_id){
                                $pas = ProductAmazonSku::query()->where('seller_sku',$_re->sku)->first();
                                $_re->psku_id = $pas->psku_id ?? 0;
                            }
                            $reportDate = date('Y-m-d',strtotime($_re->purchase_date));
                            if(!array_key_exists($_re->psku_id,$exist)){
                                $ps = ProductSku::getModelById($_re->psku_id);
                                $exist[$_re->psku_id] = $ps->classify_id ?? 0;
                            }
                            $classifyId = $exist[$_re->psku_id];
                            self::_match($reportDate,$_re->country_id,$_re->psku_id,$classifyId,$_re->quantity,$_re->tag);
                        }
                        $_re->status = 1; //1:已统计
                    }
                    $_re->save();
                }
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }
        }
    }

    /**
     * 客诉品质明细
     * @param $reportDate
     * @param $countryId
     * @param $pSkuId
     * @param $classifyId
     * @param $num
     * @param $tag
     */
    private static function _match($reportDate,$countryId,$pSkuId,$classifyId,$num,$tag){
        if($pSkuId > 0 || $classifyId > 0){
            $tags = self::_convertTag($tag);
            foreach ($tags as $_tag => $type){
                QDetail::query()->create([
                    'report_date' => $reportDate,
                    'country_id' => $countryId,
                    'psku_id' => $pSkuId,
                    'classify_id' => $classifyId,
                    'type' => $type,
                    'tag' => $_tag,
                    'num' => $num,
                ]);
            }
        }
    }

    /**
     * 标签
     * @param $tag
     * @return \Illuminate\Support\Collection
     */
    private static function _convertTag($tag){
        $tagId = QDictTag::getTagId($tag);
        return QDictTag::query()->whereIn('id',$tagId)->pluck('type','tag');
    }

    /**
     * 系统打标签：匹配退货标签
     */
    public static function dictTagCustomerReturn(){
        $qDict = QDict::all(); //Amazon标签集（字典集合）
        $res = FbaCustomerReturn::query()
            ->select('id','purchase_date','country_id','psku_id','sku','quantity','customer_comments','tag','status')
            ->where('status',0) //0:未统计
            ->get();
        $i = 0;
        $num = 500;
        while(true){
            if($res->isEmpty())break;
            $_res = $res->splice($i,$num);
            try{
                DB::beginTransaction();
                foreach($_res as $_re){
                    if(!$_re->customer_comments || !$_re->country_id){
                        $_re->status = 2; //2:无评论
                    }else{
                        $_re->tag = self::_getDictTag($qDict,$_re->customer_comments);
                    }
                    $_re->save();
                }
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }
        }
    }

    /**
     * 系统打标签：匹配客诉标签
     */
    public static function dictTagComplaint()
    {
        $qDict = QDict::all();
        $date = date('Y-m-01');
        $res = QComplaint::query()->where('status',0)->where('report_date','<',$date)->get();
        $i = 0;
        $num = 100;
        while(true){
            if($res->isEmpty())break;
            $_res = $res->splice($i,$num);
            try{
                DB::beginTransaction();
                foreach($_res as $_re){
                    if(!$_re->tag){
                        if($_re->content){
                            $_re->tag = self::_getDictTag($qDict,$_re->content);
                            $_re->save();
                        }
                    }
                }
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }
        }
    }

    private static function _getDictTag($qDict,$customerComments){
        $content = str_replace(["\r","\n","\r\n"],'',trim($customerComments));
        $re = [];
        foreach ($qDict as $_qDict){
            if(stristr($content, $_qDict->dict)){
                    $re[$_qDict->dict_tag->type][] = $_qDict->dict_tag_id;
            }
        }
        return empty($re) ? null : $re;
    }
}
